<template>
  <div>
    <el-form label-position="right" label-width="120px" ref="form" :rules="rules" :model="form">
      <el-form-item label="礼品名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入礼品名称"></el-input>
      </el-form-item>
      <el-form-item label="礼品数量" prop="num">
        <el-input v-model="form.num" placeholder="请输入礼品数量"></el-input>
      </el-form-item>
      <el-form-item label="礼品单位" prop="danwei">
        <el-input v-model="form.danwei" placeholder="请输入礼品单位-如:个,包,瓶"></el-input>
      </el-form-item>
      <el-form-item label="礼品规格" prop="guige">
        <el-input v-model="form.guige" placeholder="请输入礼品规格-如:5kg"></el-input>
      </el-form-item>
      <el-form-item label="兑换金额" prop="money">
        <el-input v-model="form.money" placeholder="请输入金额"></el-input>
      </el-form-item>
      <el-form-item label="兑换积分" prop="jifen">
        <el-input v-model="form.jifen" placeholder="请输入需要兑换的积分"></el-input>
      </el-form-item>
      <el-form-item label="礼品图片" prop="img">
        <el-upload
          action="#"
          class="manage-uploader"
          accept="image/*"
          list-type="picture-card"
          :limit="1"
          :file-list="fileList"
          :on-change="changePictureUploadAvatar"
          :auto-upload="false">
            <i class="fa fa-file-image-o imgs-uploader-icon" aria-hidden="true"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
        </el-upload>
        <p class="contract-text d2-mt-10">请保证图片格式正确，且不超过2M</p>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio label="1">正常</el-radio>
          <el-radio label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="礼品描述" prop="msg">
        <el-input v-model="form.msg" type="textarea" placeholder="请输入礼品描述"></el-input>
      </el-form-item>
      <el-form-item class="contacts-add">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="cancle">关闭</el-button>
      </el-form-item>
    </el-form>
    <!-- 摄像头使用 -->
    <el-drawer title="拍照上传" :size="500" :visible.sync="dialogVisible" @close="closeDrawer" :wrapperClosable="false" :modal="false" direction="ttb">
      <camera-module v-if="dialogVisible" ref="cameraChild" :isShowType="false" @upload="upload"></camera-module>
    </el-drawer>
    <el-dialog :visible.sync="dialogImgVisible" :close-on-click-modal="false" :append-to-body="true">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import * as APIIntegral from '@/api/integral'
import cameraModule from '@/components/camera-module'
import { uploadFilePromise, uploadDelete } from '@/api/upload'
export default {
  name: 'goods-add',
  components: {
    cameraModule
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      form: {
        status: '1',
        img: ''
      },
      dialogVisible: false,
      dialogImgVisible: false,
      dialogImageUrl: '',
      fileList: [],
      fileLists: [],
      // 表单校验
      rules: {
        name: [
          {
            required: true,
            message: '请输入礼品名称',
            trigger: 'blur'
          }
        ],
        num: [
          {
            required: true,
            message: '请输入礼品数量',
            trigger: 'blur'
          }
        ],
        danwei: [
          {
            required: true,
            message: '请输入礼品单位',
            trigger: 'blur'
          }
        ],
        guige: [
          {
            required: true,
            message: '请输入礼品规格',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 裁剪图片上传
    upload (type, imgSrc) {
      this.fileLists.push({
        name: new Date().getTime() + '.jpg',
        url: imgSrc
      })
      this.fileList.push({
        name: new Date().getTime() + '.jpg',
        url: imgSrc
      })
    },
    // 关闭弹窗
    closeDrawer () {
      // 销毁摄像头
      this.$refs.cameraChild.destoryStop()
    },
    // 放大图片
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogImgVisible = true
    },
    // 删除图片
    handleRemove (file) {
      this.fileLists.forEach((item, index) => {
        if (item.name === file.name) {
          this.fileList.splice(index, 1)
          this.fileLists.splice(index, 1)
          uploadDelete({ url: item.url })
        }
      })
      if (this.fileLists.length === 0) {
        this.form.img = ''
      }
    },
    // 上传图片
    changePictureUploadAvatar (file, fileList) {
      this.$refs.form.clearValidate(['img'])
      this.form.img = '1'
      this.fileList = fileList
      uploadFilePromise(file).then(res => {
        this.fileLists.push({
          name: file.name,
          url: res
        })
      })
    },
    // 添加老人家属
    onSubmit () {
      const imgs = []
      this.fileLists.forEach(item => {
        imgs.push(item.url)
      })
      const form = Object.assign({}, this.form, { img: imgs.join(',') })
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            APIIntegral.integralEditgoods(form).then(res => {
              this.$message({ type: "success", message: "编辑成功!"});
              this.cancle()
              this.load()
            })
          } else {
            APIIntegral.integralAddgoods(form).then(res => {
              this.$message({ type: "success", message: "新增成功!"});
              this.cancle()
              this.load()
            })
          }
        }
      })
    },
    load () {
      this.$emit('load')
    },
    cancle () {
      this.$refs.form.resetFields()
      this.$emit('cancle')
    }
  },
  watch: {
    data: {
      handler (newval) {
        this.form = newval
        let ImgArr = []
        const Arr = []
        if (newval.img) {
          ImgArr = newval.img.split(',')
          ImgArr.forEach((item, index) => {
            Arr.push({
              name: index,
              url: item
            })
          })
          this.fileList = Arr
          this.fileLists = this.fileList
        } else {
          this.fileList = []
          this.fileLists = []
        }
      },
      // 可以一进页面就触发监听器  监听器自带的immediate
      immediate: true,
      deep: true
    }
  }
}
</script>

<style lang="scss">
  .type-add-input {
    textarea {
      font-family: arial;
    }
  }
	.manage-uploader {
		.el-upload {
			width: 148px;
			height: 148px;
			border: 1px dashed #d9d9d9;
			border-radius: 6px;
			cursor: pointer;
			position: relative;
			overflow: hidden;
		}
	}
	.manage-uploader .el-upload:hover {
		border-color: #409EFF;
	}
	i.imgs-uploader-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 50px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    vertical-align: bottom;
	}
</style>
